//
//  UIScrollView+Extension.swift
//  SwiftProject
//
//  Created by qindong on 2021/3/23.
//

import Foundation

extension UIScrollView {
    private struct AssociatedKey {
        static var endPageKey : String = "endPageKey"
        static var currectPageKey : String = "currectPageKey"
    }
    var endPage : Int {
        get {
            objc_getAssociatedObject(self, &AssociatedKey.endPageKey) as? Int ?? 0
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKey.endPageKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
//            if newValue == currectPage {
//                mj_footer?.endRefreshingWithNoMoreData()
//            } else {
//                mj_footer?.endRefreshing()
//            }
            if newValue < 20 {
                if newValue == 0 {
                    (mj_footer as! MJRefreshAutoNormalFooter).stateLabel?.isHidden = true
                } else {
                    (mj_footer as! MJRefreshAutoNormalFooter).stateLabel?.isHidden = false
                }
                mj_footer?.endRefreshingWithNoMoreData()
            } else {
                mj_footer?.endRefreshing()
            }
        }
    }
    
    func endRefresh() {
        if mj_footer != nil && mj_footer!.isRefreshing {
            mj_footer!.endRefreshing()
        }
        if mj_header != nil && mj_header!.isRefreshing {
            mj_header!.endRefreshing()
        }
        if mj_trailer != nil && mj_trailer!.isRefreshing {
            mj_trailer!.endRefreshing()
        }
    }
    
    var currectPage : Int {
        get {
            objc_getAssociatedObject(self, &AssociatedKey.currectPageKey) as? Int ?? 1
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKey.currectPageKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
        }
    }
    
    func addRefresh(headerRefresh : MJRefreshComponentAction? = nil, footerRefresh : MJRefreshComponentAction? = nil) {
        if headerRefresh != nil {
            mj_header = WMRefreshHeader(refreshingBlock: headerRefresh!)
        }
        if footerRefresh != nil {
            mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: footerRefresh!)
        }
    }
}
